package cn.wx.fileclient.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.graphics.xobject.PDXObjectImage;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;

/**
 * 提取PDF中的图片
 * pdfbox 版本 1.8.13
 */
@Slf4j
public class PDF2ImageUtils {
    /**
     * 提取
     * @param file			PDF文件
     * @param targetFolder 	图片存放目录
     * @return
     */
    public static String extractImages(File file, String targetFolder,int ipage) {
        String result = "";
        try{
            PDDocument document = PDDocument.load(file);
            try {
                PDPage page = (PDPage)document.getDocumentCatalog().getAllPages().get(ipage);
                //            Iterator<PDPage> iter = pages.iterator();
                int count = 0;
                //            while( iter.hasNext()){
                //                PDPage page = (PDPage)iter.next();
                PDResources resources = page.getResources();
                Map<String, PDXObjectImage> images = resources.getImages();
                if(images != null)
                {
                    Iterator<String> imageIter = images.keySet().iterator();
                    while(imageIter.hasNext())
                    {
                        count++;
                        String key = (String)imageIter.next();
                        System.out.println(key);
                        if(key.equals("img0")){
                            PDXObjectImage image = (PDXObjectImage)images.get( key );
                            String name = file.getName() + "_" + count;	// 图片文件名
                            if(!new File(targetFolder).exists()){
                                new File(targetFolder).mkdirs();
                            }
                            result = targetFolder+"\\" + name+".jpg" ;
                            image.write2file(targetFolder+"\\" + name);		// 保存图片
                            break ;
                        }
                        //
                    }
                }
                //            }
            } catch(IOException ex){
                ex.printStackTrace();
                return result;
            }finally {
                document.close();
            }
        }catch (IOException ioExcepiton){
            log.error("文件装载失败",ioExcepiton);
        }
        return result;
    }

    public static void main(String[] args) {
        File file = new File("F:\\download\\用户资料\\1600236005211138.pdf");
        String targerFolder = "F:\\download\\用户资料\\images";

        extractImages(file, targerFolder,0);
    }
}
